package br.ufrn.cloud.gae.teamgae.jdo;

import java.util.List;

import javax.jdo.PersistenceManager;
import javax.jdo.Query;
import javax.jdo.Transaction;

import br.ufrn.cloud.gae.teamgae.model.Jogador;
import br.ufrn.cloud.gae.teamgae.model.Time;

import com.google.appengine.api.datastore.Key;

public class DAO<T> {

	private PersistenceManager pm;
	public boolean gravar(T entity){
		pm=PersistenceManagerGAE.getPersistenceManagerFactory().getPersistenceManager();
		//Transaction transaction=pm.currentTransaction();
		//transaction.begin();
		try{
			pm.makePersistent(entity);
		}finally{
			//transaction.commit();
			pm.close();
		}
		return true;
		
	}
	
	public boolean excluir(T entity){
		pm=PersistenceManagerGAE.getPersistenceManagerFactory().getPersistenceManager();
		//Transaction transaction=pm.currentTransaction();
		//transaction.begin();
		try{
			pm.deletePersistent(entity);
		}finally{
			//transaction.commit();
			pm.close();
		}
		return true;
	}
	
	public Time getTimeByKey(Key key){
		
		pm=PersistenceManagerGAE.getPersistenceManagerFactory().getPersistenceManager();
		
		Time entity=pm.getObjectById(Time.class,key);
		Time copia=pm.detachCopy(entity);
		copia.setJogadores((List<Jogador>)pm.detachCopyAll(entity.getJogadores()));
		pm.close();
		return copia;
	}
	
	public Jogador getJogadorByKey(Key key){
		pm=PersistenceManagerGAE.getPersistenceManagerFactory().getPersistenceManager();
		
		Jogador entity=pm.getObjectById(Jogador.class,key);
		Jogador copia=pm.detachCopy(entity);
		copia.setTime(pm.detachCopy(entity.getTime()));
		pm.close();
		return copia;
	}
	
	
	
}
